package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object value, Long ttl, TimeUnit timeUnit) {
        String jsonStr = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key, jsonStr, ttl, timeUnit);
    }

    public void setWithLogicalExpire(String key, Object value, Long ttl, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(ttl)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R queyWithPassThrough(String cachePrefix, ID id, Class<R> type, Function<ID,R> callback,Long ttl, TimeUnit timeUnit) {
        //1. 从redis中查询商铺
        String cacheKey = cachePrefix + id;
        String json = stringRedisTemplate.opsForValue().get(cacheKey);

        //2. 判断缓存是否命中
        if (StrUtil.isNotBlank(json)) {
            //3. 命中则直接返回
            return JSONUtil.toBean(json, type);
        }
        if(json!=null){
            return null;
        }

        //4. 未命中,则根据id查询数据库
        R r = callback.apply(id);

        //5. 数据库不存在,返回404
        if (r == null) {
            stringRedisTemplate.opsForValue().set(cacheKey,"",ttl, timeUnit);
            return null;
        }

        //6. 数据库存在,则将商铺写入redis中
        stringRedisTemplate.opsForValue().set(cacheKey,JSONUtil.toJsonStr(r),ttl, timeUnit);

        //7.返回商铺
        return r;
    }

    private final static ExecutorService EXECUTOR_SERVICE= Executors.newFixedThreadPool(10);

    public <R,ID> R queryWithLogicalExpire(String cachePrefix, ID id, Class<R> type, Function<ID,R> callback,Long ttl, TimeUnit timeUnit,String lockPrefix) {
        //1. 从redis中查询商铺
        String json = stringRedisTemplate.opsForValue().get(cachePrefix + id);

        //2. 判断缓存是否命中
        if (StrUtil.isBlank(json)) {
            //3. 命中则直接返回
            return null;
        }

        //3. 反序列化获取对象和过期时间
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = BeanUtil.toBean(redisData.getData(), type);



        //4. 判断缓存是否过期
        if(LocalDateTime.now().isAfter(redisData.getExpireTime())){
            //尝试获取互斥锁
            String lockKey = lockPrefix + id;
            boolean b = tryLock(lockKey);

            if(b){
                //5. 如果过期, 则开启独立线程, 将现有数据存到redis中
                EXECUTOR_SERVICE.execute(()->{
                    try {
                        R r1 = callback.apply(id);
                        setWithLogicalExpire(cachePrefix+id,r1,ttl,timeUnit);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        unlock(lockKey);
                    }
                });
            }

        }

        //5. 无论是否过期, 都将当前数据返回
        return r;
    }

    private boolean tryLock(String key) {
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}